import 'dart:math';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/ble/custom_service.dart';
import 'package:sgy_flutter/ble/ext.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/gen/assets.gen.dart';
import 'package:sgy_flutter/page/detail/logic.dart';
import 'package:sgy_flutter/page/detail/widget/ble_state_view.dart';
import 'package:sgy_flutter/page/detail/widget/ble_stream_view.dart';

import '../widget/device_data_view.dart';

class AxoccCenterView extends GetView<DetailLogic> {
  AxoccCenterView({super.key});

  int lastCadence = 0;
  int lastTime = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          width: 0,
          color: Get.theme.primaryColor,
        ),
        color: Get.theme.primaryColor,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 功率,踏频,左右平衡
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(28), topRight: Radius.circular(28)),
              border: Border(
                  bottom: BorderSide(color: Get.theme.primaryColor, width: 6)),
            ),
            padding: EdgeInsets.only(top: 24, bottom: 10, left: 12, right: 12),
            child: BleStateView(
              bleManager: controller.bleManager,
              builder: (connected) {
                return StreamBuilder(
                    stream: controller
                        .bleManager.cyclingPowerService.byteData.stream,
                    builder: (context, snapshot) {
                      final byteData18 = snapshot.data;
                      String? power;
                      String? cadence;
                      String? leftRightBalance;
                      String? cadenceSmooth;
                      String? torsionAvailability;
                      if (!connected) {
                        lastTime = 0;
                        lastCadence = 0;
                      }
                      printError(info: "byteData18:${byteData18?.buffer.asUint8List().toHex()}");
                      if (byteData18 != null && connected) {
                        if (byteData18!.lengthInBytes >= 4) {
                          power = "${byteData18.getUint16(2, Endian.little)}";
                        }
                        if (byteData18!.lengthInBytes >= 5) {
                          var lr = byteData18.getUint8(4) ~/ 2;
                          leftRightBalance = "${100 - lr}-${lr}";
                        }
                        if (byteData18.lengthInBytes >= 11) {
                          final currentCadence =
                              byteData18.getUint16(5, Endian.little);
                          final currentTime =
                              byteData18.getUint16(7, Endian.little);
                          if (lastCadence == 0 && lastTime == 0) {
                            lastTime = currentTime;
                            lastCadence = currentCadence;
                          } else {
                            if (currentCadence - lastCadence == 0) {
                              cadence = "0";
                            } else {
                              int myTp = (((currentTime - lastTime < 0
                                      ? currentTime - lastTime + 65536
                                      : currentTime - lastTime) ~/
                                  (currentCadence - lastCadence)));
                              if (myTp != 0){
                                cadence = "${61440 ~/ myTp}";
                              }

                              lastTime = currentTime;
                              lastCadence = currentCadence;
                            }
                          }
                        }
                      }
                      return StreamBuilder(
                          stream: controller.bleManager
                              .cyclingPowerService16.resp.stream,
                          builder: (context, snapshot) {
                            final byteData = snapshot.data;

                            if (byteData != null && connected) {
                              power ??= byteData.power;
                              cadence = byteData.cadence;
                              leftRightBalance = byteData.balance;
                            }
                            return _build(
                                power: power,
                                cadence: cadence,
                                leftRightBalance: leftRightBalance,
                                cadenceSmooth: cadenceSmooth,
                                torsionAvailability: torsionAvailability);
                          });
                    });
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _build(
      {required String? power,
      required String? cadence,
      required String? leftRightBalance,
      required String? cadenceSmooth,
      required String? torsionAvailability}) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            DeviceDataView(
                imagePath: Assets.image.iconLightning.path,
                label: "功率/W".tr,
                value: power ?? '--'),
            Container(
              width: 2,
              color: Get.theme.dividerColor,
              height: 50,
            ),
            DeviceDataView(
                imagePath: Assets.image.iconFrequency.path,
                label: "踏频/RPM".tr,
                value: cadence ?? '--'),
            Container(
              width: 2,
              color: Get.theme.dividerColor,
              height: 50,
            ),
            DeviceDataView(
              imagePath: Assets.image.iconLr.path,
              label: "左右平衡/%".tr,
              value: leftRightBalance ?? '--',
            ),
          ],
        ),

      ],
    );
  }
}
